package processing;

import javax.servlet.http.HttpServlet;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;

public class InitLog4j extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void init() {
		System.out.println("Init Webapp");
		String fileName = getInitParameter("log4j-init-file");

		FileAppender appender = getAppender(fileName);
		if (appender == null) {
			return;
		}
		initLogger(null, appender, Level.DEBUG);
	}

	private FileAppender getAppender(String fileName) {
		RollingFileAppender appender = null;
		try {
			appender = new RollingFileAppender(new PatternLayout(
					"%-5p %-20.20c %29d - %m%n"), fileName, true);
			appender.setMaxBackupIndex(5);
			appender.setMaxFileSize("1MB");
		} catch (Exception ex) {
			System.out.println("Could not create appender for " + fileName);
		}
		return appender;
	}

	private void initLogger(String name, FileAppender appender, Level level) {
		Logger logger;
		if (name == null) {
			logger = Logger.getRootLogger();
		} else {
			logger = Logger.getLogger(name);
		}
		logger.setLevel(level);
		logger.addAppender(appender);
		logger.info("Starting " + logger.getName());
	}
}
